using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Xml;
using UnityEngine;

public class UdpReceive : MonoBehaviour
{

    Socket socket;  //目标socket
    EndPoint serverEnd; //服务端
    Thread connectThread;   //连接线程
    public Queue<string> commands = new Queue<string>();
    private int RecPort = 5566, sendPort;
    private string sendip;
    
    
    string cmd = "";

    private static UdpReceive _instance = null;
    public static UdpReceive GetInstance()
    {
        if (_instance == null)
        {
            _instance = new UdpReceive();
        }
        return _instance;
    }

    private void Awake()
    {
        _instance = this;

    }

    public void Start()
    {
        RecPort = XmlConfig.GetInstance().RecPort;
        sendPort = XmlConfig.GetInstance().SendPort;
        sendip = XmlConfig.GetInstance().SendIp;
        InitSocket();
     
    }

    //private void Update()
    //{
    //    while (commands.Count > 0)
    //    {
    //        cmd = commands.Dequeue();
    //        // print("读取到udp:" + cmd);

    //        MessageCenter(cmd);

    //    }
    //    // SendUdp("我是服务端");
    //}

    //public void MessageCenter(string cmd)
    //{

    //    print(cmd);

    //    if (cmd =="0")
    //    {
            
    //    }
    
    //}

    private void OnDestroy()
    {
        SocketQuit();
    }

    public void InitSocket()
    {
        //定义服务端  
        //定义套接字类型,在主线程中定义  
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        //定义连接的服务器ip和端口，可以是本8机ip，局域网，互联网  
        //ipEnd = new IPEndPoint(IPAddress.Parse(ip), com);
        socket.Bind(new IPEndPoint(IPAddress.Any, RecPort));  //接收端
        //定义客户端
        IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
        serverEnd = (EndPoint)sender;
    

        connectThread = new Thread(ReceiveMessage);
        connectThread.IsBackground = true;
        connectThread.Start();
        Debug.Log("服务开启");
    }

    public void SendUdp(string str)
    {

        UdpClient udpSend = new UdpClient(0);
        byte[] sendbytes = Encoding.UTF8.GetBytes(str);
        IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Broadcast, sendPort);  //发送端
        udpSend.Send(sendbytes, sendbytes.Length, remoteIpep);
        udpSend.Close(); 
    }

    void ReceiveMessage()                                                                                                                               
    {
        while (true)
        {
            string message;
            byte[] data = new byte[1024];
            int length = socket.ReceiveFrom(data, ref serverEnd);
            message = Encoding.UTF8.GetString(data, 0, length);
            commands.Enqueue(message);
            Thread.Sleep(10);
        }
    }

    //连接关闭
    public void SocketQuit()
    {
        if (connectThread != null)
        {
            connectThread.Interrupt();
            try
            {
                connectThread.Abort();
            }
            catch (ThreadAbortException)
            {
            }
            catch (System.Exception ex)
            {
                Debug.LogError(ex);
            }
        }
        //最后关闭socket  
        if (socket != null)
            socket.Close();
    }
}


